package com.lienlq.voicemusic.ui;

import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.lienlq.voicemusic.R;
import com.lienlq.voicemusic.entity.MusicService;
import com.lienlq.voicemusic.entity.Track;
import com.lienlq.voicemusic.entity.TrackAdapter;

public class NowPlayingActivity extends Activity {

	private String avatarTrack = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/s32x32/275696_100003639116940_1963795429_q.jpg";
	private Context mContext;
	private ListView listView = null;
	private ImageView avatarWeb;
	private ArrayList<Track> trackList = new ArrayList<Track>();
	private TextView trackName, artist, album, amount;

	private int currentPlaying = 0;
	private boolean isBound = false;
	private boolean isPlaying = false;
	private ImageButton playBtn;
	private ImageButton nextBtn;
	private ImageButton previous;

	private Messenger mService = null;
	private final Messenger mMessenger = new Messenger(new IncomingHandler());

	private class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MusicService.MSG_UPDATE_DATA_NOWPLAYING:
				Bundle b = msg.getData();
				trackList = b
						.getParcelableArrayList(MusicService.TRACK_LIST_NAME);
				if (trackList.size() > 0) {
					Log.i("MEDIA", "Size track list : " + trackList.size()
							+ ", " + trackList);
					currentPlaying = b.getInt(MusicService.PLAYING_TRACK);
					isPlaying = b
							.getBoolean(MusicService.NAVIGATIVE_MEDIA_STATE);
					if (currentPlaying < 0
							|| currentPlaying >= trackList.size() - 1)
						currentPlaying = 0;
					Track track = trackList.get(currentPlaying);
					Log.i("MEDIA", "onNowPlayingAc : " + currentPlaying
							+ ",Length of Track List : " + trackList.size());
					Log.i("MEDIA", "onNowPlayingAc : " + track.getTrack()
							+ " Amount : " + track.getNumberListen());
					updateUI(track);
				}
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(MainActivity.ACTIVIY_LOG,
				NowPlayingActivity.class.getSimpleName());
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_now_playing2);
		mContext = this;
		bindComponents();
		doBindService();
	}

	private void bindComponents() {
		trackName = (TextView) findViewById(R.id.track_on_now_playing);
		artist = (TextView) findViewById(R.id.artist_on_now_playing);
		album = (TextView) findViewById(R.id.album_on_now_playing);
		amount = (TextView) findViewById(R.id.amount_on_now_playing);
		listView = (ListView) findViewById(R.id.tracks_list_result);
		avatarWeb = (ImageView) findViewById(R.id.avatar_img_on_now_playing2);

		playBtn = (ImageButton) findViewById(R.id.play_btn);
		playBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Message msg = Message.obtain(null,
						MusicService.MSG_NAVIGATIVE_MEDIA, 100, 0);
				try {
					mService.send(msg);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				if (!isPlaying) {
					playBtn.setImageResource(R.drawable.btn_play);

				} else {
					playBtn.setImageResource(R.drawable.btn_pause);
				}
				isPlaying = !isPlaying;
			}
		});
		nextBtn = (ImageButton) findViewById(R.id.next_btn);
		nextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ImageButton bt = (ImageButton) v;
				Message msg = Message.obtain(null,
						MusicService.MSG_NAVIGATIVE_MEDIA, 1, 0);
				try {
					mService.send(msg);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		previous = (ImageButton) findViewById(R.id.previous_btn);
		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ImageButton bt = (ImageButton) v;
				Message msg = Message.obtain(null,
						MusicService.MSG_NAVIGATIVE_MEDIA, -1, 0);
				try {
					mService.send(msg);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void updateUI(Track track) {
		if (track == null)
			return;
		trackName.setText(track.getTrack());
		artist.setText(track.getArtist());
		album.setText(track.getAlbum());
		amount.setText("" + track.getNumberListen());
		new DownloadImageTask(avatarWeb).execute(track.getImg());
		listView.setAdapter(new TrackAdapter(mContext, R.layout.item_track,
				trackList));
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Message msg = Message.obtain(null,
						MusicService.MSG_RECIEVED_TRACK_LIST);
				Bundle b = new Bundle();
				b.putInt(MusicService.PLAYING_TRACK, arg2);
				msg.setData(b);
				try {
					mService.send(msg);
				} catch (RemoteException e) {
				}
				updateUI(trackList.get(arg2));
			}
		});
		if (!isPlaying) {
			playBtn.setImageResource(R.drawable.btn_play);

		} else {
			playBtn.setImageResource(R.drawable.btn_pause);
		}
		isPlaying = !isPlaying;
	}

	private void doBindService() {
		if (MusicService.isRunning) {
			bindService(new Intent(this, MusicService.class),
					serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}

	private void doUnbindService() {
		if (isBound) {
			unbindService(serviceConnection);
			isBound = false;
		}
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(MainActivity.ACTIVIY_LOG, "Disconnected to Service");
			mService = null;
			isBound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(MainActivity.ACTIVIY_LOG, "Connected to Service");
			mService = new Messenger(service);
			isBound = true;
			Message msg = Message.obtain(null,
					MusicService.MSG_ACTIVED_NOWPLAYING);
			msg.replyTo = mMessenger;
			try {
				mService.send(msg);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
				return null;
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			if (result != null)
				bmImage.setImageBitmap(result);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "_onStart");

	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "onResume");

	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "onPause");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		doUnbindService();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "onStop");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "onRestart");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		doUnbindService();
		Log.i(MainActivity.ACTIVIY_LOG, NowPlayingActivity.class.getName()
				+ "_onDestroy");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

}
